package com.hf.action;

import javax.servlet.http.HttpSession;

import com.base.bean.*;
import com.base.dao.*;
import com.base.service.*;
import com.hf.listener.MySessionContext;

import net.sf.json.JSONObject;
import tool.*;

/**
 * 1）注册的过程：
 * （user与openId建立对应关系的过程）
 * 
 * 录入用户名 密码
 * 前端传来的参数只需要code 与sessionId
 * openId有后端获取 然后拉取用户信息并存入数据库 
 * 
 * 2）登录的过程：
 * 通过openId来查看用户权限是否满足
 * 
 * code state 都是微信回调页面传递过来的参数
 * 参考：
 * http://www.cnblogs.com/jupal/articles/5132518.html
 * @author Administrator
 *
 */
public class LoginRegist_bak extends BaseAction{
	private String code,accessToken,refreshToken,state;
	private String sessionId;
	private String username,psw;
	private String trueName,phone;
	private String nickname,headimg,company;
	
	private UserService us;
	private HttpSession session;
	
	// 后面改到配置文件或数据库中(汇发机械)
	private static String appid="wxe09104e1398974e9";
	private static String secret="66c91360cc87bf8416ea3eb4913e760c";
		
	private static String url1="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
	private static String url2="https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN";
	private static String url3="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENId&lang=zh_CN";
	
	

	/**主要是获取openId
	 * state='a'销售入口  'b'服务入口
	 */
	public String entrance(){
		User user=null;
		this.code=(code==null?"":this.code);
		this.openId=(this.openId==null?"":this.openId);
		return SUCCESS;
	}
	
	
	/**
	 * 登录过程为：
	 * 获取openId 然后将session与openId建立关联关系(在jsp页面上进行，action中不能获取到HttpSession获取的是一个map)
	 * 
	 * @return
	 */
	public String login(){
		User user=null;
		this.code=(code==null?"":this.code);
		this.openId=(this.openId==null?"":this.openId);
		this.sessionId=(this.sessionId==null?"":this.sessionId);
		this.refreshToken=(this.refreshToken==null?"":this.refreshToken);
		String result="";
		JSONObject jsonObject=null;
	try{
		if(!this.refreshToken.equals("")){	// 若有refreshToken 通过refreshToken获取openId
			result=this.getUrl(this.refreshToken,2);
			jsonObject = JSONObject.fromObject(result);
			
			this.openId=jsonObject.getString("openid");
			this.refreshToken=jsonObject.getString("refresh_token");
			this.accessToken=jsonObject.getString("access_token");
			
		}
			
		else if(!this.code.equals("")){		// 没有refreshToken的情况下 通过code获取openId refreshToken
			result=this.getUrl(this.code,1);
			jsonObject = JSONObject.fromObject(result);
			this.refreshToken=jsonObject.getString("refresh_token");
			this.accessToken=jsonObject.getString("access_token");
			this.openId=jsonObject.getString("openid");
			this.code="";
			
		}
		
	}catch(Exception e){
		//System.out.println("result:"+result);
		this.tip="获取openId出现错误"+result;
		return ERROR;
	}

	
	// 根据openId获取user
	us=UserService.getInstance();
	user=us.getByOpenId(this.openId);
	if(user==null){
		this.tip="您还没有注册请完善基本信息";
		return INPUT;
	}
	else{
		if(user.getState()==0){
			this.tip="请等待管理员审核通过";
			return ERROR;
			
		}else if(user.getState()==1){
			try{
			this.pullUserInfo();
			}catch(Exception e){
				this.tip="获取用户信息失败";
				return ERROR;					//实际时 返回可以是success
			}
			if(!this.nickname.equals(user.getNickname()) ||  !this.headimg.equals(user.getHeadurl())){
				user.setNickname(this.nickname);
				user.setHeadurl(this.headimg);
				us.getUserDao().merge(user);	//拉取的用户信息有刷新 （可以限定为多少天后才刷新）
			}

		}
	}
	
	session=MySessionContext.getSession(openId);	// login.jsp中已经将openId与session建立了关联关系
	if(session==null){
		this.tip="未找到对应的会话"+this.openId;
		System.out.println("未找到对应的会话");
		return ERROR;
	}else{
		if(user!=null)
			session.setAttribute("user", user); 	// 将user信息存入openid对应的session
	}
	
	// 显示首页显示的message消息
	
	this.tip="登录成功";
	return SUCCESS;
	}
	
	/**
	 * 注册过程：
	 * openId nickname sex headimgurl truename checked 
	 * @return
	 */
	public String regist(){	
		
		//System.out.println(this.trueName+"--"+this.company);
		
		this.nickname=(this.nickname==null?"":this.nickname);
		this.headimg=(this.headimg==null?"":this.headimg);
		
		this.accessToken=(this.accessToken==null?"":this.accessToken);
		this.openId=(this.openId==null?"":this.openId);
		this.sessionId=(this.sessionId==null?"":this.sessionId);
		
		this.trueName=(this.trueName==null?"":this.trueName);
		this.phone=(this.phone==null?"":this.phone);
		
		if(this.trueName.equals("") || this.phone.equals("")){
			this.tip="请输入您的真实姓名以及电话号码";
			return INPUT;
		}		
		
		try{
		this.pullUserInfo();		//拉去用户信息
		}catch(Exception e){
			this.tip="获取用户信息失败"+this.tip;
			return ERROR;
		}
		
		us=UserService.getInstance();
		UserDao ud = us.getUserDao();
		
		User u=new User();
		u.setHeadurl(this.headimg);
		u.setOpenid(this.openId);
		u.setName(nickname);
		u.setNickname(this.nickname);
		u.setTruename(this.trueName);
		u.setCompany(this.company);
		u.setPhone(this.phone);
		u.setState(0);	//初始状态
		
		if(ud.findByHql("from User u where u.openid='"+this.openId+"'").size()==0){
			ud.merge(u);
			this.tip="注册成功，请等待管理员审核";
			return SUCCESS;
		}else{
			this.tip="错误：该用户已经注册过";
			return ERROR;
		}
		
	}


	/**
	 * type:1 通过code换取
	 * 2：通过REFRESH_TOKEN换取
	 */
	private String getUrl(String code,int type){	//注意getopenId在父类中已经有了 
		String url="";
		if(type==1){
			url=this.url1;
			url=url.replace("SECRET",this.secret);
			url=url.replace("CODE",code);
			url=url.replace("APPID",this.appid);
			this.code="";
		}
		else if(type==2){
			url=this.url2;
			url=url.replace("REFRESH_TOKEN",code);
			url=url.replace("APPID",this.appid);	
		}	
		
		return WechatTool.readUrl(url);

	}
	
	
	// 拉取用户信息
	private void pullUserInfo() throws Exception{
		String url=this.url3;
		url=url.replace("ACCESS_TOKEN",this.accessToken);
		url=url.replace("OPENID",this.openId);
		String result="";
	try{
		result=WechatTool.readUrl(url);
		JSONObject jsonObject = JSONObject.fromObject(result);
		this.nickname=jsonObject.getString("nickname");
		this.headimg=jsonObject.getString("headimgurl");
	}catch(Exception e){
		this.tip=result;
		throw new Exception("拉取用户信息失败");
	}

	}
	
	
	
	
	
	@Override
	public String execute() {
		this.code=(code==null?"":code);
		
		
		// TODO Auto-generated method stub
		return null;
	}
	
	//test
	public static void main(String[] args){
		LoginRegist_bak g=new LoginRegist_bak();
		
		UserService us=UserService.getInstance();
		UserDao ud = us.getUserDao();
		User u=new User();
		u.setName("name");
		u.setOpenid("openid");
		ud.merge(u);
	
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getSessionId() {
		return sessionId;
	}

	public void setSessionId(String sessionId) {
		this.sessionId = sessionId;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPsw() {
		return psw;
	}

	public void setPsw(String psw) {
		this.psw = psw;
	}

	public String getTrueName() {
		return trueName;
	}

	public void setTrueName(String trueName) {
		this.trueName = trueName;
	}

	public String getPhone() {
		return phone;
	}

	public void setPhone(String phone) {
		this.phone = phone;
	}



	public String getAccessToken() {
		return accessToken;
	}

	public void setAccessToken(String accessToken) {
		this.accessToken = accessToken;
	}

	public String getRefreshToken() {
		return refreshToken;
	}

	public void setRefreshToken(String refreshToken) {
		this.refreshToken = refreshToken;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getHeadimg() {
		return headimg;
	}

	public void setHeadimg(String headimg) {
		this.headimg = headimg;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getCompany() {
		return company;
	}

	public void setCompany(String company) {
		this.company = company;
	}
	
}
